package com.codingfuture.web.controller;

import com.codingfuture.entity.Exam;
import com.codingfuture.service.ExamService;
import org.apache.poi.util.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

@Controller
public class ExamController {

    // 依赖注入
    @Autowired
    private ExamService examService;

    @RequestMapping(path = "/exam")
    public void downloadPOI(HttpServletResponse response) throws IOException {
//@RequestBody Exam[] exams,
        Exam[] exams = new Exam[3];
        Exam exam = new Exam();
        exam.setQid(3);
        exam.setScore(5);
        exams[0] = exam;

        Exam exam1 = new Exam();
        exam1.setQid(5);
        exam1.setScore(10);
        exams[1] = exam1;

        Exam exam2 = new Exam();
        exam2.setQid(6);
        exam2.setScore(15);
        exams[2] = exam2;

        response.addHeader("Content-Disposition",
                "attachment; filename=word.docx");

        OutputStream stream = examService.genExamWordStream(exams);
        ByteArrayOutputStream baos;
        baos = (ByteArrayOutputStream) stream;
        ByteArrayInputStream swapStream = new ByteArrayInputStream(baos.toByteArray());

        IOUtils.copy(swapStream, response.getOutputStream());

    }
}

